//
//  main.m
//  parseVCF
//
//  Created by My Mac on 16/5/9.
//  Copyright © 2016年 My Mac. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSString *path = @"/Users/mymac/Downloads/asd.vcf";
        NSError * err ;
        NSString *vcf = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
        if(err != nil)
        {
            NSLog(@"%@",err);
        }
        //        NSLog(@"%@",vcf);
        NSArray *arr = [vcf componentsSeparatedByString:@"\n"];
        NSMutableArray *db = [NSMutableArray new];
        NSMutableDictionary *dict ;
        
        for (NSString *line in arr){
            if([line hasPrefix:@"BEGIN"])
            {
                NSLog(@"开始一条语句");
                dict = [NSMutableDictionary new];
            }
            if ([line hasPrefix:@"END"])
            {
                NSLog(@"这条语句结束了");
                [db addObject:dict];
                
            }
            if([line hasPrefix:@"TEL"])
            {
                NSLog(@"找到一条电话记录！%@",line);
                NSArray *tels = [line componentsSeparatedByString:@":"];
                NSString *last = tels.lastObject;
                //                last =[last substringFromIndex:5];
                NSLog(@"tel:%@",last);
                dict [@"tel"]=last;
            }
            if([line hasPrefix:@"FN"])
            {
                NSLog(@"姓名");
                NSArray *names = [line componentsSeparatedByString:@":"];
                NSString *name = names.lastObject;
                name = [name stringByReplacingOccurrencesOfString:@"=" withString:@"%"];
                name = name.stringByRemovingPercentEncoding;
                NSLog(@"name:%@",name);
                dict [@"name"]= name;
                
            }
            
        }
        NSLog(@"%@",db);
        [db writeToFile:@"/Users/mymac/Downloads/db.txt"atomically:NO];
        NSData *data = [NSJSONSerialization dataWithJSONObject:db options:NSJSONWritingPrettyPrinted error:nil];
        [db writeToFile:@"/Users/mymac/Downloads/db.txt" atomically:NO];
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        
        NSMutableArray *db2 = [NSMutableArray new];
        for (NSDictionary *dict in db) {
            Person *p = [Person new];
            [p setValuesForKeysWithDictionary:dict];
            [db2 addObject:p];
        }
        NSLog(@"%@",db2);
    }
    return 0;
}
